
package com.hlkj.pay.controller.openapi.callback;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.json.JSONObject;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.finance.IFinanceRecordAppService;
import com.hlkj.pay.app.merchant.ext.MerchantExtConstant;
import com.hlkj.pay.app.order.*;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.util.HttpRequestUtil;
import com.hlkj.pay.vo.order.OpenApiResult;
import com.hlkj.pay.vo.order.resp.PayOrderResp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HlpayTeam
 * @date 2024/09/12 11:32
 */
@Tag(name = "商户交易第三方回调")
@RestController
@RequestMapping("")
@RequiredArgsConstructor
public class OrderPayCallBackController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(OrderPayCallBackController.class);

    private final IPayOrderAppService payOrderAppService;

    private final IRefundOrderAppService refundOrderAppService;

    private final IFinanceRecordAppService financeRecordAppService;
    private final ITransferOrderAppService transferOrderAppService;
    private final IWithdrawOrderAppService withdrawOrderAppService;
    private final IComplaintOrderAppService complaintOrderAppService;

    @Value("${hlkj.defaultRedirectUrl}")
    private String defaultRedirectUrl;


    @Operation(summary = "支付订单状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANS_ASYNC_CALLBACK_URL + "/{channelCode}/{providerCode}", produces = { "text/plain", "application/*" }, method = {RequestMethod.GET, RequestMethod.POST})
    String payOrderStatusCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode, HttpServletRequest request) {
        //国广支付 订单支付与退款回调走的同一个地址，判断退款加此分支
        if (channelCode.equals(MerchantExtConstant.CHANNEL_GUOG_PAY)) {
            String requestBody = HttpRequestUtil.requestBodyParams(request);
            JSONObject obj = JsonUtils.parseObj(requestBody);
            if (obj.containsKey("outRefundNo"))
                return refundOrderAppService.refundCallBack(channelCode, providerCode, request);
        }else if(channelCode.equals(MerchantExtConstant.CHANNEL_YYT_PAY)){
            String requestBody = HttpRequestUtil.requestBodyParams(request);
            JSONObject obj = JsonUtils.parseObj(requestBody);
            JSONObject data = obj.getJSONObject("data");
            if(!data.isEmpty()){
                if (data.containsKey("trans_type") && data.getStr("trans_type").equals("refund")){
                    return refundOrderAppService.refundCallBack(channelCode, providerCode, request);
                }
            }
        }
        return payOrderAppService.orderStatusCallBack(channelCode, providerCode, request);
    }

    @Operation(summary = "商户订单状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANS_COMMON_ASYNC_CALLBACK_URL + "/{channelCode}/{providerCode}/{mchChannelCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String mchPayOrderStatusCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode,@PathVariable("mchChannelCode") String mchChannelCode, HttpServletRequest request) {
        return payOrderAppService.mchOrderStatusCallBack(channelCode,providerCode,mchChannelCode,request);
    }

    @Operation(summary = "H5订单状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANS_ASYNC_CALLBACK_URL + "/{channelCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String payOrderStatusCallBack(@PathVariable("channelCode") String channelCode, HttpServletRequest request) {
        return payOrderAppService.orderStatusCallBack(channelCode, request);
    }

    @Operation(summary = "支付订单同步跳转")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANS_FORWARD_CALLBACK_URL + "/{orderNo}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    void payOrderCallBack(@PathVariable("orderNo") String orderNo, HttpServletResponse response) {
        try {
            CommonResult<String> result = payOrderAppService.queryRedirectUrl(orderNo);
            if (result.isSuccess()) response.sendRedirect(result.getData());
            else response.sendRedirect(defaultRedirectUrl);
        } catch (Exception e) {
        }
    }

    @Operation(summary = "关闭订单状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANS_CLOSE_ASYNC_CALLBACK_URL + "/{channelCode}/{providerCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String closeOrderCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode, HttpServletRequest request) {
        return payOrderAppService.closeOrderCallBack(channelCode, providerCode, request);
    }

    @Operation(summary = "商户关闭订单状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANS_COMMON_CLOSE_ASYNC_CALLBACK_URL + "/{channelCode}/{providerCode}/{mchChannelCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String closeOrderCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode, @PathVariable("mchChannelCode") String mchChannelCode,HttpServletRequest request) {
        return payOrderAppService.closeOrderCallBack(channelCode, providerCode, mchChannelCode,request);
    }

    @Operation(summary = "退款状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_REFUND_ASYNC_CALLBACK_URL + "/{channelCode}/{providerCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String refundCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode, HttpServletRequest request) {
        return refundOrderAppService.refundCallBack(channelCode, providerCode, request);
    }

    @Operation(summary = "商户退款状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_REFUND_COMMON_ASYNC_CALLBACK_URL + "/{channelCode}/{providerCode}/{mchChannelCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String mchRefundCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode,@PathVariable("mchChannelCode") String mchChannelCode, HttpServletRequest request) {
        return refundOrderAppService.refundCallBack(channelCode, providerCode,mchChannelCode, request);
    }

    @Operation(summary = "充值状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_RECHARGE_ASYNC_CALLBACK_URL, produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String rechargeCallBack(@RequestBody OpenApiResult<PayOrderResp> orderRespOpenApiResult) {
        return financeRecordAppService.rechargeCallBack(orderRespOpenApiResult);
    }

    @Operation(summary = "测试回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TEST_CALLBACK_URL, produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String testCallBack(@RequestBody OpenApiResult<Object> objectOpenApiResult) {
        log.info("test 接收到的回调参数为:{}", JsonUtils.toJsonString(objectOpenApiResult));
        return "success";
    }

    @Operation(summary = "转账订单状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANSFER_TRANS_ASYNC_CALLBACK_URL + "/{channelCode}/{providerCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String transferOrderStatusCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode, HttpServletRequest request) {
        return transferOrderAppService.orderStatusCallBack(channelCode, providerCode, request);
    }

    @Operation(summary = "提现订单状态回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANSFER_WITHDRAW_ASYNC_CALLBACK_URL + "/{channelCode}/{providerCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String withdrawOrderStatusCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode, HttpServletRequest request) {
        return withdrawOrderAppService.orderStatusCallBack(channelCode, providerCode, request);
    }

    @Operation(summary = "订单投诉回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_ORDER_COMPLAINT_CALLBACK_URL + "/{id}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String complaintOrderCallBack(@PathVariable("id") Long id, HttpServletRequest request) {
        return complaintOrderAppService.complaintCallBack(id, request);
    }

    @Operation(summary = "订单风险回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_ORDER_RISK_CALLBACK_URL + "/{id}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String riskOrderCallBack(@PathVariable("id") Long id, HttpServletRequest request) {
        return complaintOrderAppService.riskCallBack(id, request);
    }

    @Operation(summary = "订单清算回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_ORDER_CS_CALLBACK_URL + "/{channelCode}/{providerCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String csOrderCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode, HttpServletRequest request) {
        return payOrderAppService.csOrderCallBack(channelCode, providerCode, request);
    }

    @Operation(summary = "分账订单回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_ORDER_DIVICE_CALLBACK_URL + "/{channelCode}/{providerCode}/{batchNo}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String divideOrderCallBack(@PathVariable("channelCode") String channelCode, @PathVariable("providerCode") String providerCode, @PathVariable("batchNo") String batchNo,HttpServletRequest request) {
        return payOrderAppService.diviceOrderCallBack(channelCode, providerCode,batchNo, request);
    }


    @Operation(summary = "商户授权回调")
    @RequestMapping(value = MerchantExtConstant.MERCHANT_TRANS_ALIPAY_AUTH_CALLBACK_URL+ "/{channelCode}", produces = "text/plain", method = {RequestMethod.GET, RequestMethod.POST})
    String merAuthStatusCallBack(@PathVariable("channelCode") String channelCode,HttpServletRequest request) {
        return payOrderAppService.merAuthStatusCallBack(channelCode,request);
    }
}
